package com.glory.brepda.view;

import android.content.Context;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;

import androidx.annotation.Nullable;
import androidx.recyclerview.widget.DefaultItemAnimator;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.BaseViewHolder;
import com.glory.brepda.R;
import com.pda.platform.ui.ui_pdaplatform.dialog.FreeUI_GeneralPop;
import com.pda.platform.ui.ui_pdaplatform.utils_public.FreeApi_PopUtils;
import com.pda.platform.ui.ui_pdaplatform.view.FreeUI_ClearEditText;

import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;

/**
 * 可增删的下拉框控件：
 * - 输入框有内容时显示右侧“+”图标，点击添加到下拉列表（去重，保序）；
 * - 点击下拉箭头，弹出列表；每项右侧显示“-”删除图标，点击可移除；
 * - 支持初始化传入列表；支持选中项回调、列表变更回调。
 */
public class AddRemoveDropdownView extends LinearLayout {

    // 对应的 view_add_remove_dropdown view 组件
    private EditText etInput;
    private ImageView ivAdd;
    private ImageView ivArrow;
    private LinearLayout llContainer;
    private FreeUI_GeneralPop pop;

    // 初始化传入的列表
    private final List<String> items = new ArrayList<>();

    // 定义外部回调方法接口
    // 列表元素被选择时回调
    public interface OnItemSelectedListener { void onItemSelected(String item, int position); }
    // 列表变更时回调
    public interface OnItemsChangedListener { void onItemsChanged(List<String> newItems); }

    private OnItemSelectedListener onItemSelectedListener;
    private OnItemsChangedListener onItemsChangedListener;

    public AddRemoveDropdownView(Context context) { super(context); init(context); }
    public AddRemoveDropdownView(Context context, @Nullable AttributeSet attrs) { super(context, attrs); init(context); }
    public AddRemoveDropdownView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(context); }

    private void init(Context context) {
        setOrientation(VERTICAL);
        LayoutInflater.from(context).inflate(R.layout.view_add_remove_dropdown, this, true);
        llContainer = findViewById(R.id.llContainer);
        etInput = findViewById(R.id.etInput);
        ivAdd = findViewById(R.id.ivAdd);
        ivArrow = findViewById(R.id.ivArrow);

        // 输入变化时，控制“+”的显隐
        etInput.addTextChangedListener(new android.text.TextWatcher() {
            @Override public void beforeTextChanged(CharSequence s, int start, int count, int after) { }
            @Override public void onTextChanged(CharSequence s, int start, int before, int count) {
                ivAdd.setVisibility(s != null && s.toString().trim().length() > 0 ? View.VISIBLE : View.GONE);
            }
            @Override public void afterTextChanged(android.text.Editable s) { }
        });

        // 添加：输入不为空且不重复 -> 添加，并触发列表变更回调
        ivAdd.setOnClickListener(v -> {
            // 轻量点击动效：缩放再回弹
            v.animate().cancel();
            v.animate()
                .scaleX(0.75f)
                .scaleY(0.75f)
                .setDuration(80)
                .withEndAction(() -> v.animate().scaleX(1f).scaleY(1f).setDuration(120))
                .start();
            
            // 获取文本框内容
            String text = etInput.getText().toString().trim();
            if (text.isEmpty()) return;
            // 去重
            if (!items.contains(text)) {
                items.add(text);
                dedupeInPlace();
                // 触发外部回调方法
                notifyItemsChanged();
            }
        });

        // 定义 OnclickListener -> 展开下拉
        View.OnClickListener showListener = v -> {
            // 若展开，则收起
            if (pop != null && pop.isShowing()) { pop.dismiss(); }
            // 构建下拉列表 ， adapter string -> PopItem
            PopItemAdapter adapter = new PopItemAdapter(new ArrayList<>(items));
            pop = buildPop(getContext(), llContainer.getWidth(), adapter, ivArrow, (ty, i) -> {
                etInput.setText(ty);
                if (onItemSelectedListener != null) onItemSelectedListener.onItemSelected(ty, i);
            });
            FreeApi_PopUtils.setArrowShow(ivArrow);
            pop.showAsDropDown(llContainer, 0, 0);
        };
        ivArrow.setOnClickListener(showListener);
        llContainer.setOnClickListener(showListener);
    }

    public void setOnItemSelectedListener(OnItemSelectedListener l) { this.onItemSelectedListener = l; }
    public void setOnItemsChangedListener(OnItemsChangedListener l) { this.onItemsChangedListener = l; }

    private void notifyItemsChanged() {
        if (onItemsChangedListener != null) onItemsChangedListener.onItemsChanged(getItems());
    }

    /**
     * 过滤掉重复项
     */
    private void dedupeInPlace() {
        LinkedHashSet<String> set = new LinkedHashSet<>(items);
        items.clear();
        items.addAll(set);
    }

    /**
     * 构建下拉列表 view
     */
    private FreeUI_GeneralPop buildPop(Context context, int width, PopItemAdapter popListAdapter, final ImageView ivArrow,
                                        final com.pda.platform.ui.ui_pdaplatform.callback.FreeUI_TextAndPositionCallback callback) {
        View mView = LayoutInflater.from(context).inflate(com.pda.platform.ui.ui_pdaplatform.R.layout.free_ui_pop_choose_list, (ViewGroup) null);
        RecyclerView recyclerView = mView.findViewById(com.pda.platform.ui.ui_pdaplatform.R.id.rvList);
        recyclerView.setLayoutManager(new LinearLayoutManager(context));
        recyclerView.setItemAnimator(new DefaultItemAnimator());
        recyclerView.addItemDecoration(new DividerItemDecoration(context, DividerItemDecoration.VERTICAL));
        final FreeUI_GeneralPop generalPop = new FreeUI_GeneralPop(context, mView, width, -2);
        popListAdapter.openLoadAnimation(1);
        popListAdapter.isFirstOnly(true);
        popListAdapter.setOnItemClickListener((adapter, view, position) -> {
            callback.onSuccess(String.valueOf(adapter.getItem(position)), position);
            generalPop.dismiss();
        });
        recyclerView.setAdapter(popListAdapter);
        generalPop.setOutsideTouchable(true);
        generalPop.setOnDismissListener(() -> FreeApi_PopUtils.setArrowMiss(ivArrow));
        return generalPop;
    }

    /**
     * 列表项转换 Adapter
     */
    private class PopItemAdapter extends BaseQuickAdapter<String, BaseViewHolder> {
        PopItemAdapter(List<String> data) { super(R.layout.item_removed_pop_list, data); }

        @Override
        protected void convert(BaseViewHolder helper, String item) {
            helper.setText(R.id.tvItem, item);
            // 点击删除 ， 过滤掉列表中该项，并同步列表
            helper.getView(R.id.ivItemRemove).setOnClickListener(v -> {
                items.remove(item);
                dedupeInPlace();
                notifyItemsChanged();
                // 同步弹窗列表
                getData().remove(item);
                notifyDataSetChanged();
            });
        }
    }


    public void setItems(List<String> list) {
        items.clear();
        if (list != null) items.addAll(list);
        dedupeInPlace();
        notifyItemsChanged();
    }

    public List<String> getItems() { return new ArrayList<>(items); }

    public String getInputText() { return etInput.getText().toString().trim(); }

    public void setInputText(String text) { etInput.setText(text); }
}